<?php
/*
Plugin Name: Link Page to Category
Plugin URI: http://oursky.com/
Description: Redirect page to category by meta key *link_to_category*
Author: Oursky
Version: 1.0
Author URI: http://oursky.com
*/

/*
Usage / Setting:
    For use to turn a page into category page:
        1. Custom field: 'link_to_category', with the category name as the value

    For the page template:
        1. Call os_linkcat_get_query('[key name]') to get the posts's WP_QUERY object
*/
if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); }

// For the page template which using link_to_category metakey, call this function to get the related posts natively.
function os_linkcat_get_query($keyname = "link_to_category") {
	global $post;
    $cat_names = get_post_meta($post->ID, $keyname);

    for ($i = 0; $i < count($cat_names); $i++) {
        $cat_ids[] = get_cat_ID($cat_names[$i]);
    }

    $cat_ids_line = os_linkcat_to_string_with_seperator($cat_ids);
    if(count($cat_ids) > 0)
        return new WP_Query("cat=$cat_ids_line");
    else
        return NULL;
}

function os_linkcat_to_string_with_seperator($arr, $seperator = ",") {
    $line = "";
    for ($i = 0; $i < count($arr); $i++) {
        $line = $line.$arr[$i];
        if ($i < count($arr) -1) {
            $line = $line.$seperator;
        }
    }
    return $line;
}

function os_linkcat_template_redirect() {
    $query = os_linkcat_get_query();
    if($query != NULL) {
        global $wp_query;
        $wp_query = $query;
        if(file_exists(TEMPLATEPATH . '/category.php')) {
            require(TEMPLATEPATH . '/category.php');
        } elseif(file_exists(TEMPLATEPATH . '/archive.php')) {
            require(TEMPLATEPATH . '/archive.php');
        } else {
            require(TEMPLATEPATH . '/index.php');
        }
        exit;
    }
}

add_action("template_redirect", "os_linkcat_template_redirect");

?>